package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sun.security.krb5.internal.APOptions;

/**
 * admin网关全局过滤器
 */
@Slf4j
@Component
public class AuthorizerFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("admin网关拦截到请求...");
        //1.获取request . response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (request.getURI().getPath().contains("/login")) {
            //2.判断是否为登录,如果是登录则放行
            return chain.filter(exchange);
        }
        //获取token,判断token是否为空
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        //解析令牌

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //-1：有效，0：有效，1：过期，2：过期
            int verifyToken = AppJwtUtil.verifyToken(claimsBody);
            if (verifyToken == 1 || verifyToken == 2) {
                //令牌过期,拦截
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //令牌解析ok   解析令牌中的用户id,存入到header中携带到下游微服务中
            Object userId = claimsBody.get("id");
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();
            //重置请求头
            exchange.mutate().request(serverHttpRequest);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析异常");
            //拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
